<?php

namespace FoxLib\Middleware;

use App\Facades\Consumer;
use Closure;
use FoxLib\Exceptions\InvalidRequestException;
use Illuminate\Http\Request;


class OauthConsumerMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  \String $consumer
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $consumer)
    {
        $requestConsumer = $request->header("X-Consumer-Username");

        if ($requestConsumer !== $consumer) {
            throw new InvalidRequestException();
        }

        $requestUserId = $request->header("X-Authenticated-Userid");
        $requestScopes = explode(',', $request->header("X-Authenticated-Scope"));
        app('consumerContext')->initialize($requestConsumer, $requestUserId, $requestScopes);
        
        return $next($request);
    }
}
